//
//  LiveStreamUploadConfigurationViewController.swift
//  live
//
//  Created by melvyn on 2018/8/16.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import LFLiveKit
import Alarmer

class LiveStreamUploadConfigurationViewController: UIViewController {
    
    @IBOutlet weak var textFiled: UITextField!
    @IBOutlet weak var thumbnailButton: UIButton!
    @IBOutlet weak var openLiveStreamButton: UIButton!
    @IBOutlet weak var shutdownButton: UIButton!
    @IBOutlet weak var orientationButton: UIButton!
    @IBOutlet weak var captureDevicePositionButton: UIButton!
    @IBOutlet weak var roomNumberTextLabel: UILabel!
    @IBOutlet weak var avatar: UIImageView!
    
    weak var viewModel: LiveStreamUploadRoomViewModel?
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .allButUpsideDown
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        shutdownButton.imageView?.tintColor = .white
        var image = shutdownButton.imageView?.image
        shutdownButton.setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)
        
        thumbnailButton.imageView?.contentMode = .scaleAspectFill
        thumbnailButton.imageView?.clipsToBounds = true
        
        orientationButton.imageView?.tintColor = .white
        image = orientationButton.imageView?.image
        orientationButton.setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)
        
        captureDevicePositionButton.imageView?.tintColor = .white
        image = captureDevicePositionButton.imageView?.image
        captureDevicePositionButton.setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)
        
        guard let viewModel = viewModel else { return }
        
        viewModel.metadata
            .asDriver()
            .map { UIImage.init(data: $0) }
            .drive(thumbnailButton.rx.image())
            .disposed(by: disposeBag)
        
        viewModel.isEnabled
            .drive(openLiveStreamButton.rx.isEnabled)
            .disposed(by: disposeBag)
        
        viewModel.roomID
            .drive(roomNumberTextLabel.rx.text)
            .disposed(by: disposeBag)
        
        viewModel.avatar
            .drive(avatar.rx.image)
            .disposed(by: disposeBag)
        
        openLiveStreamButton.rx.tap
            .bind(to: viewModel.openLiveStream)
            .disposed(by: disposeBag)
        
        shutdownButton.rx.tap
            .bind(to: viewModel.shutdown)
            .disposed(by: disposeBag)
        
        textFiled.rx.text
            .map { $0 ?? "" }
            .bind(to: viewModel.title)
            .disposed(by: disposeBag)
        
        thumbnailButton.rx.tap
            .flatMap { [weak self]_ -> Observable<UIImagePickerController.SourceType> in
                Alarmer.rx.present(by: self, configuration: { (observer) -> Alarmer in
                    let alarmer = Alarmer.init(title: "封面选择", message: "请选择封面", preferredStyle: .actionSheet)
                    
                    let library = Action.init(title: "Library", style: .default) { (action) in
                        observer.onNext(.photoLibrary)
                        observer.onCompleted()
                    }
                    
                    let camera = Action.init(title: "Camera", style: .default) { (action) in
                        observer.onNext(.camera)
                        observer.onCompleted()
                    }
                    
                    let cancel = Action.init(title: "取消", style: .cancel, handler: nil)
                    
                    alarmer.addAction(library)
                    alarmer.addAction(camera)
                    alarmer.addAction(cancel)
                    
                    return alarmer
                })
                    .take(1)
                    .delay(0.5, scheduler: MainScheduler.instance)
            }
            .flatMap({ [weak self] sourceType in
                return UIImagePickerController.rx.present(by: self, animated: true, configuration: { (picker) in
                    picker.sourceType = sourceType
                    picker.allowsEditing = false
                })
                    .flatMap({ $0.rx.didFinishPickingMediaWithInfo })
                    .take(1)
            })
            .map({
                $0[UIImagePickerController.InfoKey.originalImage] as! UIImage
            })
            .map({
                ImageJPEGRepresentation($0, 0.5) ?? Data()
            })
            .bind(to: viewModel.metadata)
            .disposed(by: disposeBag)
        
        orientationButton.rx.tap
            .bind(onNext: { _ in
                let orientation: UIInterfaceOrientationMask
                if UIApplication.shared.statusBarOrientation.isPortrait {
                    orientation = .landscapeRight
                } else {
                    orientation = .portrait
                }
                UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
            })
            .disposed(by: disposeBag)
        
        captureDevicePositionButton.rx.tap
            .map { _ in LiveSession.default.captureDevicePosition == .back ? .front : .back }
            .bind(to: LiveSession.default.rx.captureDevicePosition)
            .disposed(by: disposeBag)
    }
}

